<?php
require_once dirname(__FILE__) . '/oss/alioss.class.php';
require_once dirname(__FILE__) . '/oss/util/oss_util.class.php';

/**
 * Author: Hancock
 * Email: 84622365@qq.com
 * Date: 10/15/2015
 * Time: 9:48 AM
 * Des:阿里云 OSS操作类
 */
class oss extends ALIOSS
{
    private $static_url = "http://sta.dekahome.cn/";
    private $bucket = "zhizhuangwang";
    private $object;
    private $size;
    var $file;

    /**
     * 上传文件
     * @param $file
     * @param string $object
     * @param string $type
     * @return array
     */
    public function upload($file, $object = '', $type = 'image')
    {
        $this->file = $file;
        $this->object = $object;
        if ($this->file["error"] > 0) {
            return $this->msg(false, $this->file["error"]);
        }
        if (!is_file($this->file['tmp_name'])) {
            return $this->msg(false, '文件不存在');
        }

        switch ($type) {
            case 'image':
                return $this->uploadImage();
                break;
            default:
                break;
        }
    }

    /**
     * 上传图片
     * @param $file
     * @param string $path
     * @param bool|false $name
     * @return array
     */
    public function uploadImage($file, $path = '', $name = false)
    {
        $this->file = $file;
        if ((!$this->imageType($this->file['type'])) || (!$this->imageSize($this->file['size']))) {
            return $this->msg(false, '该文件不是图片或者超最大文件大小限制');
        }
        $content = '';
        $length = 0;
        $fp = fopen($this->file["tmp_name"], 'r');
        if ($fp) {
            $f = fstat($fp);
            $length = $f['size'];
            while (!feof($fp)) {
                $content .= fgets($fp, 30720);
            }
        }

        if ($name === true) {
            $ext = explode('.', $this->file["name"]);
            $file_name = time() . '_' . rand(0, 9) . '.' . $ext[1];
        } elseif ($name === false) {
            $file_name = $this->file["name"];
        } else {
            $file_name = $name;
        }

        if ($path != '') {
            $file_name = $path . '/' . $file_name;
        }

        $upload_file_options = array('content' => $content, 'length' => $length);
        $res = $this->upload_file_by_content($this->bucket, $file_name, $upload_file_options);
        if ($res->status == 200) {
            return $this->msg(true, $file_name);
        } else {
            return $this->msg(false, 'oss code:' . $res->status);
        }
    }

    /**
     * 上传文件
     * @param $file
     * @return array
     * @throws OSS_Exception
     */
    public function uploadFile($file)
    {    
        if (strstr(SITE_ROOT, 'hanguang.com')) {
            return $this->msg(true, true);
        }

        $file = trim($file, '.');
        $this->file = trim($file, '/');
        if (!is_file($file)) {
            return $this->msg(false, 'fail:' . $file);
        }
        $res = $this->upload_file_by_file($this->bucket, $this->file, $file);
        if ($res->status == 200) {
            return $this->msg(true, $file);
        } else {
            return $this->msg(false, 'oss code:' . $res->status);
        }
    }

    /**
     * 列出当前目录object
     * @param string $options
     * @return array
     */
    public function list_object($options, $bucket = '')
    {
        return OSSUtil::parse_response(parent::list_object($this->bucket, $options));
    }

    /**
     * 删除object
     * @param string $object
     * @param string $options
     * @return array
     */
    public function delete_object($object, $options, $bucket = '')
    {
        return OSSUtil::parse_response(parent::delete_object($this->bucket, $object, $options));
    }

    /**
     * 判断是否是图片
     * @param $type
     * @return bool
     */
    private function imageType($type)
    {
        $imageType = array();
        $imageType[] = 'image/gif';
        $imageType[] = 'image/jpeg';
        $imageType[] = 'image/pjpeg';
        $imageType[] = 'image/png';
        if (in_array($type, $imageType)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 图片大小限制
     * @param $size
     * @return bool
     */
    private function imageSize($size)
    {
        $this->size = 31457280;//30M
        if ($size > $this->size) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 返回信息
     * @param $status
     * @param string $msg
     * @return array
     */
    private function msg($status, $msg = '')
    {
        return array('status' => $status, 'msg' => trim($msg));
    }

    /**
     * 获取文件
     * @param $response
     * @return array
     */
    private function getObjectsByBody($response)
    {
        $objects = $response['body']['ListBucketResult']['Contents'];
        $data = array();
        if (array_key_exists('Key', $objects)) {
            $data[] = $objects['Key'];
        } else {
            foreach ($objects as $value) {
                $data[] = $value['Key'];
            }
        }
        return $data;
    }

    /**
     * 获取文件夹
     * @param $response
     * @return array
     */
    private function getPrefixByBody($response)
    {
        $prefix = $response['body']['ListBucketResult']['CommonPrefixes'];
        $data = array();
        if (sizeof($prefix) == 1) {
            $data[] = $prefix['Prefix'];
        } else {
            foreach ($prefix as $value) {
                $data[] = $value['Prefix'];
            }
        }
        return $data;
    }

    /**
     * 遍历bucket获取所有object
     * @param $options
     * @param array $data
     * @return array
     */
    public function getAllObjects($options, $data = array())
    {
        $res = $this->list_object($options);
        $objects = $this->getObjectsByBody($res);
        if (sizeof($objects) > 0) {
            foreach ($objects as $value) {
                $data[] = $value;
            }
        }

        $prefix = $this->getPrefixByBody($res);
        if (sizeof($prefix) > 0) {
            foreach ($prefix as $value) {
                $data[] = $value;
                $sub_options = array(
                    'prefix' => $value
                );
                $data = $this->getAllObjects($sub_options, $data);
            }
        }
        return $data;
    }

    /**
     * 删除文件夹下所有文件
     * @param $prefix
     * @return bool
     */
    public function delByPrefix($prefix)
    {
        $options = array(
            'prefix' => $prefix
        );
        $objects = array_reverse($this->getAllObjects($options));
        foreach ($objects as $object) {
            $this->delete_object($object);
        }
        return true;
    }

    public function getCache($object)
    {
        if (LOCAL) {
            return false;
        } elseif ($this->is_object_exist($this->bucket, $object)) {
            return OSS_IMAGE_URL . "cache/" . $object;
        } else {
            return false;
        }
    }

    /**
     * 上传文件夹
     * @param $dir
     * @return array
     */
    public function uploadDir($dir)
    {
        if (strstr(SITE_ROOT, 'hanguang.com')) {
            return $this->msg(true, true);
        }

        if (!is_dir(ROOT_PATH . $dir)) {
            return $this->msg(false, 'fail:' . ROOT_PATH . $dir);
        }
        $res = $this->upload_object_by_dir($this->bucket, $dir);
        if ($res['status'] == 200) {
            return $this->msg(true, 1);
        } else {
            return $this->msg(false, $res['msg']);
        }
    }

    public function download($object)
    {
        mkdir(ROOT_PATH . dirname($object), 0777, true);
        $file_path = $object;
        $option = [
            'delimiter' => '/',
            'prefix' => $file_path,
        ];
        $objects = @$this->getAllObjects($option);
        foreach ($objects as $key => $value) {
            if (substr($value, strlen($value) - 1) == '/') {
                if (!file_exists($value)) {
                    mkdir(ROOT_PATH . $value, 0777, true);
                }
            } else {
                file_put_contents(ROOT_PATH . $value, file_get_contents($this->static_url . $value));
            }
        }
    }
}
